package com.jihu.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jihu.mall.common.constant.ProductConstant;
import com.jihu.mall.common.to.SkuReductionTo;
import com.jihu.mall.common.to.SpuBoundTo;
import com.jihu.mall.common.to.es.SkuEsModel;
import com.jihu.mall.common.utils.R;
import com.jihu.mall.product.entity.*;
import com.jihu.mall.product.feign.CouponFeignService;
import com.jihu.mall.product.feign.SearchFeignService;
import com.jihu.mall.product.feign.WareFeignService;
import com.jihu.mall.product.service.*;
import com.jihu.mall.product.vo.*;
import com.jihu.mall.product.vo.request.SkuHasStock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.event.ItemEvent;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihu.mall.common.utils.PageUtils;
import com.jihu.mall.common.utils.Query;

import com.jihu.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * //TODO 远程服务异常事务回滚
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = saveBaseSpuinfo(spuSaveVo);
        //2.保存spu的描述图片 pms_spu_info_desc
        saveSpuinfoDesc(spuSaveVo, spuInfoEntity);
        //3.保存spu的图片集 pms_spu_images
        saveSpuinfoImages(spuSaveVo,spuInfoEntity.getId());
        //4.保存spu的规格参数 pms_product_attr_value
        saveProcuctAttrValue(spuSaveVo,spuInfoEntity.getId());
        //5.保存spu的积分信息 sms_spu_bounds
        saveSpuBounds(spuSaveVo,spuInfoEntity);
        //6.保存当前spu对应的所有sku信息
        saveAllSkuInfo(spuSaveVo,spuInfoEntity);
    }


    //1.保存spu基本信息 pms_spu_info
    private SpuInfoEntity saveBaseSpuinfo(SpuSaveVo spuSaveVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuinfo(spuInfoEntity);
        return spuInfoEntity;
    }

    //2.保存spu的描述图片 pms_spu_info_desc
    private void saveSpuinfoDesc(SpuSaveVo spuSaveVo, SpuInfoEntity spuInfoEntity) {
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        this.saveSpuinfoDesc(descEntity);
    }

    //3.保存spu的图片集 pms_spu_images
    private void saveSpuinfoImages(SpuSaveVo spuSaveVo,Long spuId) {
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuId,images);
    }

    //4.保存spu的规格参数 pms_product_attr_value
    private void saveProcuctAttrValue(SpuSaveVo spuSaveVo,Long spuId) {
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> entities = baseAttrs.stream().map(attr -> {
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        saveProcuctAttrValue(entities);
    }

    //5.保存spu的积分信息 sms_spu_bounds
    private void saveSpuBounds(SpuSaveVo spuSaveVo, SpuInfoEntity spuInfoEntity) {
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保存积分信息失败");
        }
    }


    //6.保存当前spu对应的所有sku信息
    private void saveAllSkuInfo(SpuSaveVo spuSaveVo, SpuInfoEntity spuInfoEntity) {
        //6.1.sku基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if(!CollectionUtils.isEmpty(skus)){
            skus.forEach(sku ->{
                String defaultImg = "";
                for (Images images: sku.getImages()) {
                    if(images.getDefaultImg() == 1){
                        defaultImg = images.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuinfo(skuInfoEntity);

                //6.2.sku图片信息 pms_sku_images
                saveSkuImgaes(sku,skuInfoEntity);
                //6.3.sku的销售属性：pms_sku_sale_attr_value
                saveSkuProcuctAttrValue(sku,skuInfoEntity);
                //6.4.sku的优惠、满减信息 sms--- sms_sku_ladder/sms_sku_full_reduction/sms_member_price
                saveSkuReduction(sku,skuInfoEntity);
            });
        }

    }

    //6.2.sku图片信息 pms_sku_images
    private void saveSkuImgaes(Skus sku,SkuInfoEntity skuInfoEntity) {
        List<SkuImagesEntity> collect = sku.getImages().stream().map(img -> {
            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
            skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
            skuImagesEntity.setImgUrl(img.getImgUrl());
            skuImagesEntity.setDefaultImg(img.getDefaultImg());
            return skuImagesEntity;
        }).filter(img ->{
            //返回true就是需要 false就是剔除
            return !StringUtils.isEmpty(img.getImgUrl());
        }).collect(Collectors.toList());
        skuImagesService.saveBatch(collect);
    }

    //6.3.sku的销售属性：pms_sku_sale_attr_value
    private void saveSkuProcuctAttrValue(Skus sku,SkuInfoEntity skuInfoEntity) {
        List<SkuSaleAttrValueEntity> collect = sku.getAttr().stream().map(attr -> {
            SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
            BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
            skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
            return skuSaleAttrValueEntity;
        }).collect(Collectors.toList());
        skuSaleAttrValueService.saveBatch(collect);
    }

    //6.4.sku的优惠、满减信息 sms--- sms_sku_ladder/sms_sku_full_reduction/sms_member_price
    private void saveSkuReduction(Skus sku, SkuInfoEntity skuInfoEntity) {
        SkuReductionTo skuReductionTo = new SkuReductionTo();
        BeanUtils.copyProperties(sku,skuReductionTo);
        skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
        if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
            R r = couponFeignService.saveSkuReduction(skuReductionTo);
            if(r.getCode() != 0){
                log.error("远程保存sku优惠信息失败");
            }
        }

    }


    @Override
    public void saveBaseSpuinfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveSpuinfoDesc(SpuInfoDescEntity descEntity) {
        spuInfoDescService.save(descEntity);
    }

    @Override
    public void saveProcuctAttrValue(List<ProductAttrValueEntity> entities) {
        productAttrValueService.saveBatch(entities);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<SpuInfoEntity>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w ->{
                w.eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq(SpuInfoEntity::getPublishStatus,status);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq(SpuInfoEntity::getBrandId,brandId);
        }
        String catalogId = (String) params.get("catalogId");
        if(!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)){
            wrapper.eq(SpuInfoEntity::getCatalogId,catalogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);

    }

    @Override
    @Transactional
    public void up(Long spuId) {
        //1.查询出当前spuId对应的所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);

        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 4、查询当前的sku所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListforspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs1);
                    return attrs1;
                })
                .collect(Collectors.toList());

        //TODO 1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> skuMap = null;
        try {
            R r = wareFeignService.getSkusHasStock(skuIdList);
            //
            skuMap = r.getData(new TypeReference<List<SkuHasStock>>(){}).stream().collect(Collectors.toMap(SkuHasStock::getSkuId, Item -> Item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常:原因{}",e);
        }

        //2.封装每个sku的信息
        Map<Long, Boolean> finalSkuMap = skuMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);

            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            if(finalSkuMap == null){
                esModel.setHasStock(false);
            }else{
                esModel.setHasStock(finalSkuMap.get(sku.getSkuId()));
            }

            //TODO 2、热度评分，0
            esModel.setHasScore(0L);

            //TODO 3、查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());

        //TODO 5、将数据发送给es进行保存 mall-search:
        R r = searchService.productStatusUp(upProducts);
        if(r.getCode() == 0){
            //远程调用成功
            //TODO 6、修改当前spu状态
            baseMapper.updateSpuStatus(spuId,ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //远程调用失败
            //TODO 7、重复调用？接口幂等性：重试问题
            //Feign调用流程
            /**
             * 1.构造请求数据，将对象转为json
             *  RquestTemplate template = buildTemplateFromArgs.create(argv);
             * 2.发送请求进行执行（执行成功解码并响应数据）
             *  executeAndDecode(template)
             * 3.执行请求会有重试机制
             *  while(true){
             *      try{
             *         executeAndDecode(template);
             *      }catch(){
             *         try{retryer.continueOrPropagate(e);}catch(){throw ex;}
             *         continue;
             *      }
             *
             *  }
             *
             */
        }
    }


}